package com.yanqu.road.dao.impl.player;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.banquet.UserCrossBanquetData;
import com.yanqu.road.entity.banquet.cross.CrossBanquetMember;
import com.yanqu.road.entity.player.UserBaseInfo;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserCrossBanquetDaoImpl extends TempDataObjectDao<UserCrossBanquetData> {


    public Map<Long, CrossBanquetMember> getCrossBanquetMemberMap(String banquetId) {
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_c_banquet_member where banquetId = ?";
        Map<Long, CrossBanquetMember> res = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setString(i++,banquetId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossBanquetMember data = parseMember(rs);
                res.put(data.getUserId(),data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return res;
    }

    protected CrossBanquetMember parseMember(ResultSet rs) throws SQLException {
        CrossBanquetMember data = new CrossBanquetMember();
        data.setBanquetId(rs.getString("banquetId"));
        data.setUserId(rs.getLong("userId"));
        data.setRobot(rs.getBoolean("robot"));
        data.setRobotProcessId(rs.getInt("robotProcessId"));
        data.setRobotId(rs.getInt("robotId"));
        data.setGiftId(rs.getInt("giftId"));
        data.setPopularity(rs.getLong("popularity"));
        data.setIntegral(rs.getLong("integral"));
        data.setPos(rs.getInt("pos"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setNoneOption();
        return data;
    }

    public Map<String, UserCrossBanquetData> getRunningUserCrossBanquetMap() {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<String, UserCrossBanquetData> res = new ConcurrentHashMap<>();
        //正常开启的宴会还没有领奖的，非正常开启的宴会且時間在十分鐘以内
        {
            String sql = "select * from t_u_banquet_cross where isSendReward = 0 and status = 1";
            try {
                getDb().setConnName(DbNameStrategy.getUserDb());
                call = getDb().getConnection().prepareCall(sql);
                rs = call.executeQuery();
                while (rs.next()) {
                    UserCrossBanquetData data = parse(rs);
                    res.put(data.getBanquetId(),data);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                getDb().closeConnection(call, rs);
            }
        }
        {
            String sql = "select * from t_u_banquet_cross where status = 0 and openTime + 10*60*1000 > ?";
            try {
                getDb().setConnName(DbNameStrategy.getUserDb());
                call = getDb().getConnection().prepareCall(sql);
                int i = 1;
                call.setLong(i++, System.currentTimeMillis());

                rs = call.executeQuery();
                while (rs.next()) {
                    UserCrossBanquetData data = parse(rs);
                    res.put(data.getBanquetId(), data);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                getDb().closeConnection(call, rs);
            }
        }
        return res;
    }

    @Override
    protected boolean addData(UserCrossBanquetData data) {
        PreparedStatement call = null;
        String sql = "INSERT INTO t_u_banquet_cross(serverId,userId,banquetId,type,openTime,overTime,isSendReward," +
                "popularity,integral,userCount,userBaseInfo,serverList,invitationId,invitationInfo,status,giftTypeAccept,message,autoOpen)" +
                " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getServerId());
            call.setLong(i++, data.getUserId());
            call.setString(i++, data.getBanquetId());
            call.setInt(i++, data.getType());
            call.setLong(i++, data.getOpenTime());
            call.setLong(i++, data.getOverTime());
            call.setBoolean(i++, data.isSendReward());
            call.setLong(i++, data.getPopularity());
            call.setLong(i++, data.getIntegral());
            call.setInt(i++, data.getUserCount());
            call.setString(i++, data.getUserBaseInfoJsonStr());
            call.setString(i++, data.getServerListStr());
            call.setString(i++, data.getInvitationId());
            call.setString(i++, data.getInvitationInfo());
            call.setInt(i++, data.getStatus());
            call.setString(i++, data.getGiftTypeAccept());
            call.setString(i++, data.getMessage());
            call.setInt(i++, data.getAutoOpen());

            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserCrossBanquetData data) {
        PreparedStatement call = null;
        String sql = "UPDATE t_u_banquet_cross SET openTime=?,overTime=?,isSendReward=?,popularity=?,integral=?,userCount=?,status=?,giftTypeAccept=?,message=?,autoOpen=? where banquetId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getOpenTime());
            call.setLong(i++, data.getOverTime());
            call.setBoolean(i++, data.isSendReward());
            call.setLong(i++, data.getPopularity());
            call.setLong(i++, data.getIntegral());
            call.setLong(i++, data.getUserCount());
            call.setInt(i++, data.getStatus());
            call.setString(i++, data.getGiftTypeAccept());
            call.setString(i++, data.getMessage());
            call.setInt(i++, data.getAutoOpen());

            call.setString(i++, data.getBanquetId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserCrossBanquetData parseData(ResultSet rs) throws SQLException {
        UserCrossBanquetData data = new UserCrossBanquetData();
        data.setBanquetId(rs.getString("banquetId"));
        data.setServerId(rs.getInt("serverId"));
        data.setUserId(rs.getLong("userId"));
        data.setType(rs.getInt("type"));
        data.setOpenTime(rs.getLong("openTime"));
        data.setOverTime(rs.getLong("overTime"));
        data.setSendReward(rs.getBoolean("isSendReward"));
        data.setPopularity(rs.getLong("popularity"));
        data.setIntegral(rs.getLong("integral"));
        data.setUserCount(rs.getInt("userCount"));
        data.setServerListStr(rs.getString("serverList"));
        data.setStatus(rs.getInt("status"));
        data.setInvitationId(rs.getString("invitationId"));
        data.setInvitationInfo(rs.getString("invitationInfo"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo) {
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setGiftTypeAccept(rs.getString("giftTypeAccept"));
        data.setMessage(rs.getString("message"));
        if (data.getMessage() == null) {
            data.setMessage("");
        }
        data.setAutoOpen(rs.getInt("autoOpen"));
        return data;
    }

}
